<!-- 组织选择 -->
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import * as orgApi from '@/api/org'
import type Node from 'element-plus/es/components/tree/src/model/node'
import useNotic from '@/hooks/useNotic'

const emits = defineEmits(['pick'])

const showDialog = ref(false)
// 当前选中节点数据
const curNode = ref<any>(null)

const treeData = reactive({
  list: [] as any[],
  props: { label: 'orgName', isLeaf: 'isLeaf', children: 'children' },
  keyword: ''
})

/**
 * 弹窗初始化
 */
function init() {
  curNode.value = null
  showDialog.value = true
}
/**
 * 树节点加载事件
 */
function treeLoadEvt(node: Node) {
  let params = {}
  // 根节点加载
  if (node.level === 0) {
    params = { initOrg: 1 }
  }
  // 子节点加载
  else {
    params = { parentId: node.data.id }
  }

  return new Promise((resolve) => {
    orgApi.getChildrenByOrgId(params).then((res) => {
      if (res.success) {
        const normalList = res.data.rows
        resolve(normalList)
      }
    })
  })
}
/**
 * 点击节点
 */
function nodeClick(data: any) {
  curNode.value = data
}
/**
 * 点击确定
 */
function confirmClick() {
  if (!curNode.value) {
    useNotic().warning('请选择组织')
    return
  }
  emits('pick', curNode.value)
  showDialog.value = false
}

defineExpose({
  init
})
</script>

<template>
  <div style="display: inline-block" @click="showDialog = true">
    <slot></slot>
    <dui-dialog v-model="showDialog" title="选择组织" width="500px">
      <dui-lazy-tree :load="treeLoadEvt" :props="treeData.props" @node-click="nodeClick" />
      <template #footer>
        <el-button @click="showDialog = false">关闭</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </template>
    </dui-dialog>
  </div>
</template>
